package auth

import (
	"system-admin/config/mysql"
	"system-admin/internal/models"
)

// AddRemoteMonitorAuth 自动增加远程监控权限
// 原来拥有远程维护权限的，自动增加95、87、98远程维护权限
func AddRemoteMonitorAuth() {
	db := mysql.NewDB()
	var rule0 models.AuthRule
	var rule1 models.AuthRule
	var rule2 models.AuthRule
	var rule3 models.AuthRule
	rowsAffected0 := db.Model(&models.AuthRule{}).
		Where("name = ?", "remote-control").
		Take(&rule0).RowsAffected
	rowsAffected1 := db.Model(&models.AuthRule{}).
		Where("name = ?", "remote-control-index").
		Take(&rule1).RowsAffected
	rowsAffected2 := db.Model(&models.AuthRule{}).
		Where("name = ?", "remote-control-97").
		Take(&rule2).RowsAffected
	rowsAffected3 := db.Model(&models.AuthRule{}).
		Where("name = ?", "remote-control-98").
		Take(&rule3).RowsAffected
	// 原有权限的id
	// 新的子权限id
	if rowsAffected0 == 1 && rowsAffected1 == 1 && rowsAffected2 == 1 && rowsAffected3 == 1 {
		var roleAuthRules []models.RoleAuthRule
		db.Model(&models.RoleAuthRule{}).
			Where("rule_id = ?", rule0.ID).
			Find(&roleAuthRules)
		// 为每个拥有远程维护的角色追加新的子权限
		for _, roleAuthRule := range roleAuthRules {
			// 增加导航管理权限
			var count1 int64
			db.Model(&models.RoleAuthRule{}).
				Where("role_id = ? AND rule_id = ?", roleAuthRule.RoleID, rule1.ID).
				Count(&count1)
			if count1 == 0 {
				db.Model(&models.RoleAuthRule{}).Create(&models.RoleAuthRule{
					RoleID: roleAuthRule.RoleID,
					RuleID: rule1.ID,
				})
			}
			// 增加售卖屏权限
			var count2 int64
			db.Model(&models.RoleAuthRule{}).
				Where("role_id = ? AND rule_id = ?", roleAuthRule.RoleID, rule2.ID).
				Count(&count2)
			if count2 == 0 {
				db.Model(&models.RoleAuthRule{}).Create(&models.RoleAuthRule{
					RoleID: roleAuthRule.RoleID,
					RuleID: rule2.ID,
				})
			}
			// 增加媒体屏权限
			var count3 int64
			db.Model(&models.RoleAuthRule{}).
				Where("role_id = ? AND rule_id = ?", roleAuthRule.RoleID, rule3.ID).
				Count(&count3)
			if count3 == 0 {
				db.Model(&models.RoleAuthRule{}).Create(&models.RoleAuthRule{
					RoleID: roleAuthRule.RoleID,
					RuleID: rule3.ID,
				})
			}
		}
	}
}
